package com.bigger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bigger.constant.ErrorConstant;
import com.bigger.context.BaseContext;
import com.bigger.dto.LoginDTO;
import com.bigger.dto.UpdatePasswordDTO;
import com.bigger.entity.Employee;
import com.bigger.exception.LoginException;
import com.bigger.exception.PowerException;
import com.bigger.mapper.EmployeeMapper;
import com.bigger.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Employee login(LoginDTO loginDTO) {
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<Employee>()
                .eq("username",loginDTO.getUsername());
        Employee employee = employeeMapper.selectOne(queryWrapper);
        if(employee==null){
            throw new LoginException(ErrorConstant.USER_NOT_EXIST);
        }
        String password = employee.getPassword();
        String loginPassword = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes(StandardCharsets.UTF_8));
        if (!password.equals(loginPassword)){
            throw new LoginException(ErrorConstant.PASSWORD_ERROR);
        }
        return employee;
    }

    @Override
    public void updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        Employee employee = employeeMapper.selectByUsername(updatePasswordDTO.getUsername());
        if(employee==null){
            throw new LoginException(ErrorConstant.USER_NOT_EXIST);
        }
        if (!employee.getId().equals(BaseContext.getCurrentId())){
            throw new PowerException(ErrorConstant.INSUFFICIENT_PRIVILEGES);
        }
        String password = employee.getPassword();
        String oldPassword = DigestUtils.md5DigestAsHex(updatePasswordDTO.getOldPassword().getBytes(StandardCharsets.UTF_8));
        if (!password.equals(oldPassword)){
            throw new LoginException(ErrorConstant.OLD_PASSWORD_ERROR);
        }
        String newPassword = DigestUtils.md5DigestAsHex(updatePasswordDTO.getNewPassword().getBytes(StandardCharsets.UTF_8));
        employee.setPassword(newPassword);
        employee.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        employeeMapper.updateById(employee);
    }

    @Override
    public Employee getById() {
        Employee employee = employeeMapper.selectById(BaseContext.getCurrentId());
        return employee;
    }
}
